package com.codingfuture.erp_system.web.controller;

import com.codingfuture.erp_system.dto.InventoryDto;
import com.codingfuture.erp_system.dto.PageData;
import com.codingfuture.erp_system.service.InventoryService;
import com.codingfuture.erp_system.util.Result;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/v2")
public class InventoryController {
    @Autowired
    private InventoryService inventoryService;

    //    渲染数据
    @GetMapping("/inventory/listByPage")
    public Result findByAll(@RequestParam(defaultValue = "1") int page,
                            @RequestParam(defaultValue = "10") int rows,
                            InventoryDto inventoryDto) {
        Page<InventoryDto> page1 = PageHelper.startPage(page, rows);
        List<InventoryDto> list = inventoryService.findByAll(inventoryDto);
        PageData<InventoryDto> data = new PageData<>(list, page1.getTotal());
        return Result.ok(data);
    }

    //    新增数据
    @PostMapping("/inventory/add")
    public Result insert(InventoryDto inventoryDto, HttpSession session) {
        Object uuid = session.getAttribute("uuid");
        inventoryDto.setCreatename((Integer) uuid);
        boolean insert = inventoryService.insert(inventoryDto);
        return insert ? Result.ok() : Result.error(200, "失败");
    }

    //    获取goodList
    @GetMapping("/inventory/goodsList")
    public Result findGood() {
        List<InventoryDto> list = inventoryService.findGood();
        return Result.OK(list);
    }

    //获取storeList
    @GetMapping("/inventory/storeList")
    public Result findStore() {
        List<InventoryDto> list = inventoryService.findStore();
        return Result.OK(list);
    }

    //    回显
    @GetMapping("/inventory/selectone")
    public Result findId(Integer id, HttpSession httpSession) {
        httpSession.setAttribute("inventoryId", id);
        InventoryDto inventoryDto = inventoryService.findById(id);
        return inventoryDto != null ?
                Result.OK(inventoryDto) :
                Result.error(500, "服务端错误");
    }

    //    编辑
    @PostMapping("/inventory/update")
    public Result update(InventoryDto inventoryDto, HttpSession session) {
        Object id = session.getAttribute("inventoryId");
        inventoryDto.setUuid((Integer) id);
        boolean update = inventoryService.update(inventoryDto);
        return update ? Result.ok() : Result.error(500, "失败");
    }

    //    删除
    @DeleteMapping("/inventory")
    public Result delete(Integer id) {
        inventoryService.delete(id);
        return Result.ok();
    }


}
